﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using System.Reflection;
using System.Collections.ObjectModel;

using System.Threading;
using System.IO;


namespace NovelSpider
{

    
    public partial class Main : Form
    {
        public Main()
        {
            InitializeComponent();
            initMsgBox();
            CheckForIllegalCrossThreadCalls = false;
        }

        public static ListBox MsgBox;
        /// <summary>
        /// 动态创建静态控件
        /// </summary>
        private void initMsgBox()
        {
            // 
            // MsgBox
            // 
            MsgBox = new ListBox();
            MsgBox.BackColor = SystemColors.InfoText;
            MsgBox.Dock = DockStyle.Fill;
            MsgBox.ForeColor = SystemColors.Info;
            MsgBox.ItemHeight = 12;
            MsgBox.Location = new Point(3, 17);
            MsgBox.Name = "MsgBox";
            MsgBox.SelectionMode = SelectionMode.None;
            MsgBox.Size = new Size(902, 88);
            MsgBox.TabIndex = 100;
            this.gbOutPut.Controls.Add(MsgBox);
        }

        

        /// <summary>
        /// 当前使用的存储接口
        /// </summary>
        private IStorager ist = null;


        private static MsgLevel _LogLevel;
        /// <summary>
        /// 获取消息日志级别
        /// </summary>
        public static MsgLevel LogLevel
        {
            get { return _LogLevel; }
        }


        private void Main_Load(object sender, EventArgs e)
        {

        }

        void ip_ChapterHasGot(object sender, ChapterEventArgs e)
        {
            Log.PrintLog(MsgLevel.Debug,"章节详情:" + e.Chapter.Name + ":" + e.Chapter.Content + "==>" + e.NovelInfo.Name);
            if (ist != null)
            {
                ist.SaveChapter(e.Chapter);
            }
        }

        void ip_ChapterListHasGot(object sender, ChapterListEventArgs e)
        {
            Log.PrintLog(MsgLevel.Debug, "章节列表:" + e.NovelInfo.Name);
            foreach (ListViewItem lvi in this.LVRemote.Items)
            {
                if (lvi.SubItems[0].Text.Equals(e.NovelInfo.Name) &&　e.ChapterList.Count > 1)
                {
                    lvi.SubItems[1].Text = e.ChapterList[e.ChapterList.Count - 1].Name;
                }
            }
        }

        void ip_VolumeListHasGot(object sender, VolumeListEventArgs e)
        {
            Log.PrintLog(MsgLevel.Debug, "分卷列表:" + e.NovelInfo.Name);
        }

        void ip_NovelInfoHasGot(object sender, NovelInfoEventArgs e)
        {
            Log.PrintLog(MsgLevel.Debug, "作者:" + e.NovelInfo.Author.Name);
            Log.PrintLog(MsgLevel.Debug, "摘要:" + e.NovelInfo.Summary);
            Log.PrintLog(MsgLevel.Debug, "状态:" + e.NovelInfo.Status.ToString());
            Log.PrintLog(MsgLevel.Debug, "封面:" + e.NovelInfo.CoverUri.AbsoluteUri);

            if (ist != null)
            {
                ist.SaveNovelInfo(e.NovelInfo);
            }
        }

        void ip_NovelListHasGot(object sender, NovelListEventArgs e)
        {
            Log.PrintLog(MsgLevel.Debug, "小说列表,数量：" + e.NovelList.Count);
            foreach (NovelInfo novel in e.NovelList)
            {
                string[] item = {novel.Name,string.Empty};
                this.LVRemote.Items.Add(new ListViewItem(item));
            }
        }

        void ip_ProcedureHasFinished(object sender, ProcFinishEventArgs e)
        {
            Log.PrintLog(MsgLevel.Debug, "线程结束，消耗时间：" + e.UsedTime.Seconds.ToString() + "秒");
            this.StartToolStripMenuItem.Enabled = true;
        }

        private void StartToolStripMenuItem_Click(object sender, EventArgs e)
        {
            try
            {
                Log.PrintLog(MsgLevel.Info, "开始调度");
                Dispatch dispatch = new Dispatch();

                if (dispatch.ShowDialog() == DialogResult.OK)
                {
                    ist = dispatch.iStorager;//保存存储接口
                    if(dispatch.Crontab == Cron.RightNow)//立即执行
                    {
                        this.RunJob(dispatch);
                    }
                    else if(dispatch.Crontab == Cron.DelayOnce)//计划任务
                    {
                        System.Timers.Timer time = new System.Timers.Timer(dispatch.Delay * 60 * 1000);
                        time.AutoReset = true;
                        time.Elapsed += new System.Timers.ElapsedEventHandler(time_Elapsed);
                        //...
                    }
                    else
                    {
                        
                    }
                }
                Log.PrintLog(MsgLevel.Info, "结束调度");

            }
            catch (Exception ex)
            {
                MessageBox.Show(ex.Message);
            }
        }

        void time_Elapsed(object sender, System.Timers.ElapsedEventArgs e)
        {
            //throw new NotImplementedException();
        }



        private void RunJob(Dispatch dispatch)
        {
            foreach (JobItem job in dispatch.Jobs)
            {
                ICollector ic = Function.GetCollectorPluginInterface(job.AssemblyPath);


                if (ic == null)
                    throw new Exception("Invalid PluginInterface.");

                ic.NovelListHasGot += new NovelListGotEventHandler(ip_NovelListHasGot);
                ic.NovelInfoHasGot += new NovelInfoGotEventHandler(ip_NovelInfoHasGot);
                ic.VolumeListHasGot += new VolumeListEventHandler(ip_VolumeListHasGot);
                ic.ChapterListHasGot += new ChapterListGotEventHandler(ip_ChapterListHasGot);
                ic.ChapterHasGot += new ChapterGotEventHandler(ip_ChapterHasGot);
                ic.ProcedureHasFinished += new ProcedureFinishEventHandler(ip_ProcedureHasFinished);

                ic.Run(job.TargetSite);
                this.StartToolStripMenuItem.Enabled = false;
            }
        }

       

        private void 退出ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            Application.Exit();
        }

        private void ToolStripMenuItem_Click(object sender, EventArgs e)
        {
            ToolStripMenuItem tsmi = sender as ToolStripMenuItem;

            严重ToolStripMenuItem.Checked = false;
            警告ToolStripMenuItem.Checked = false;
            提示ToolStripMenuItem.Checked = false;
            调试ToolStripMenuItem.Checked = false;
            tsmi.Checked = true;
            _LogLevel = (MsgLevel)Enum.Parse(typeof(MsgLevel), tsmi.Tag.ToString());

            Log.PrintLog(MsgLevel.Critical, "消息级别设置为：" + _LogLevel.ToString());
        }




       

    }
}
